package com.yixing.tech.wcs;

import lombok.Data;
import lombok.NoArgsConstructor;

public class ProducerConsumerDemo {

    @Data
    @NoArgsConstructor
    public static class Bread {
        private String name;
        private int count = 1;
        private boolean flag = false;
    }

    @Data
    @NoArgsConstructor
    public static class Producer implements Runnable {
        private Bread b;        // 生产者的成员，要处理的资源

        public Producer(Bread b) {
            this.b = b;
        }

        public void produce(String name) {
            b.name = name + b.count;
            b.count++;
        }

        @Override
        public void run() {
            while(true) {
                synchronized (Bread.class) {
                    if(b.flag) {
                        try {
                            Bread.class.wait();
                        }catch (InterruptedException e) {
//                            throw new RuntimeException(e);
                        }
                    }
                    produce("面包");
                    System.out.println(Thread.currentThread().getName() + "----生产者----" + b.name);
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    b.flag = true;
                    Bread.class.notify();

                }
            }
        }
    }

    @Data
    @NoArgsConstructor
    public static class Consumer implements Runnable {

        private Bread b;
        Consumer(Bread b) {
            this.b = b;
        }

        public String consume() {
            return this.b.name;
        }

        @Override
        public void run() {
            while(true) {
                synchronized (Bread.class) {
                    if(!b.flag) {
                        try {
                            Bread.class.wait();
                        } catch (InterruptedException e) {
//                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println(Thread.currentThread().getName() + "----消费者----" + consume());
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
//                        throw new RuntimeException(e);
                    }
                    b.flag = false;
                    Bread.class.notify();
                }
            }
        }
    }

    public static void main(String[] args) {
        Bread b = new Bread();

        Producer producer = new Producer(b);
        Consumer consumer = new Consumer(b);

        Thread proT = new Thread(producer);
        Thread consT = new Thread(consumer);
        proT.start();
        consT.start();
    }
}
